package com.zzc.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zzc.fwzpxt.entity.Article;
import com.zzc.fwzpxt.service.IArticleService;
import com.zzc.common.controller.BaseController;
import com.zzc.common.result.JsonResult;
import com.zzc.sys.entity.Menu;
import com.zzc.sys.entity.User;
import com.zzc.sys.service.IPermissionService;
import com.zzc.sys.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 主页、登陆
 * Created by XiaoBingBy on 2017/9/23.
 */
@Controller
@RequestMapping(value = "/admin")
public class IndexController extends BaseController {

    @Autowired
    private IPermissionService iPermissionService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IArticleService iArticleService;

    // 主页
    @RequestMapping(value = "/index")
    public String index(Model model) {
        // 获取当前用户菜单
        List<Menu> menus = iPermissionService.createMenu(getCurrentLoginId());
        model.addAttribute("menus",menus);
        model.addAttribute("userInfo", this.getCurrentUser());
        return "/admin/index";
    }

    @RequestMapping(value = "index_v1")
    public String index_v1(Model model) {
        EntityWrapper<Article> wrapper = new EntityWrapper<>();
        wrapper.eq("article_type", 2);
        Article article = iArticleService.selectOne(wrapper);
        model.addAttribute("article", article);
        return "/admin/index_v1";
    }

    /**
     * 获取当前登陆用户信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getcurrentuser")
    public JsonResult getcurrentuser() {
        return renderSuccess(this.getCurrentUser());
    }

    @ResponseBody
    @RequestMapping(value = "/updatecurrentuser")
    public JsonResult updatecurrentuser(User user) {
        if (user!= null && user.getPassword() != null && user.getPassword() != "") {
            String salt = String.valueOf(System.currentTimeMillis());
            SimpleHash password = new SimpleHash("MD5", user.getPassword(), salt);
            user.setSalt(salt);
            user.setPassword(password.toString());
        }
        user.setId(this.getCurrentLoginId());
        return iUserService.updateById(user) ? renderSuccess("修改成功") : renderError("修改失败");
    }


    /**
     * 登陆页面
     * @return
     */
    @GetMapping("/login")
    public String loginForm() {
        return "/admin/login";
    }

    /**
     * 登陆提交页面
     * @param username
     * @param password
     * @param map
     * @return
     */
    @RequestMapping("/mylogin")
    public String mylogin(String username, String password, Map<String, Object> map) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            String simpleName = e.getClass().getSimpleName();
            if ("UnknownAccountException".equals(simpleName)) {
                map.put("msg", "用户不存在");
                return "/admin/login";
            } else if("IncorrectCredentialsException".equals(simpleName)){
                map.put("msg", "密码不正确");
                return "/admin/login";
            }
        }
        boolean authenticated = subject.isAuthenticated();
        if (authenticated) {
            return "redirect:/admin/index.html";
        }
        return "redirect:/admin/login.html";
    }

}
